var Favourites = (function () {
	var fav_guideline, fav_guidelineTimer;
	var fav_buf1 = "<div class=\"programPage\" style=\"overflow-y:hidden; width: 278px;height: HEIGHTpx;overflow-x:hidden;\"><div class=\"programLeft\">&nbsp;<br></div><div class=\"programContent\" style=\"height: 100%; font-size: 1.3em; background: #EDEEEB none repeat scroll 0 0 !important;\">";
	var fav_buf2 = "<div class=\"shortinfo\"><div><div style=\"width: 270px;position:relative;top:8px;\">";
	var fav_buf3 = "</div></div></div><div style=\"clear:both\"></div></div><!-- content end --></div><!-- page end -->";
	var fav_buf4 = "document.body.style.width = \"281px\";document.body.style.height = height + \"px\";var content = document.getElementById(\"flyoutContentFrame\");content.innerHTML = buffer;content.style.width = \"280px\";content.style.height = height + \"px\";content = document.getElementById(\"flyoutMainFrame\");content.style.height = height + \"px\";content.style.width = \"280px\";";
	var fav_suggest1 = "<div height=\"0\" width=\"192\" name=\"xml_suggestionsInner\" autoscroll=\"true\"  background=\"#FAFAFA\" x=\"1\" y=\"1\"></div>";
	var fav_suggest2 = "<button image=\"stock_images/scrollup_u.png\" overImage=\"stock_images/scrollup_o.png\" width=\"12\" height=\"10\" x=\"90%\" y=\"3\" tooltip=\"Hide\"/>";
	var fav_suggest3 = "<label name=\"xml_time_slice\" x=\"0\" y=\"0\" height=\"12\" width=\"97%\" color=\"#3CC040\" size=\"7\" align=\"center\"></label>";
	var fav_suggest4 = "<div x=\"0\" y=\"13\" name=\"xml_suggestionsContainer\" width=\"100%\" height=\"100%\"></div>";
	var fav_initialized = false;
	var fav_object = null;
	var fav_optgroup = null;
	var fav_input = null;
	var fav_suggestionBox = null;
	var fav_chanArray = null;
	var fav_chanToMonitor = null;
	var fav_upcomingPrograms = [];
	var fav_monitorWindow = [];
	var fav_lastSearch = "";
	function fav_buildMonitor() {
		if (vverbose) {
			log(__FUNCTION());
		}
		if (fav_upcomingPrograms == null || fav_upcomingPrograms.length == 0) {
			return;
		}
		var buffer;
		var daystrings = [strings.SUNDAY, strings.MONDAY, strings.WEDNESDAY, strings.THURSDAY, strings.FRIDAY, strings.SATURDAY];
		var monthstrings = [strings.JAN, strings.FEB, strings.MAR, strings.APR, strings.MAY, strings.JUN, strings.JUL, strings.SEP, strings.OCT, strings.NOV, strings.DEC];
		var program, now = new Date;
		now = daystrings[now.getDay()] + " d. " + now.getDate() + " " + monthstrings[now.getMonth()];
		buffer = fav_buf1.replace(/HEIGHT/, fav_upcomingPrograms.length * 66);
		for (var i = 0; i < fav_upcomingPrograms.length; i++) {
			program = fav_upcomingPrograms[i];
			buffer += "<h1 style=\"padding-bottom: 6px;\">" + program.title + "</h1>";
			buffer += fav_buf2 + program.channel + "| " + now + " <b>" + program.start + " - " + program.end + "</b>";
			buffer += fav_buf3;
		}
		buffer += "<script type=\"text/javascript\">" + "var height = " + fav_upcomingPrograms.length * 66 + ";" + fav_buf4 + "</script>";
		return buffer;
	}

	function fav_closeSuggest() {
		if (vverbose) {
			log(__FUNCTION());
		}
		if (fav_suggestionBox != null) {
			fav_suggestionBox.visible = false;
			xml_suggestionsContainer.removeAllElements();
			return;
		}
	}

function fav_loadMonitor() {
	if (vverbose) {
		log(__FUNCTION());
	}
	if (g_Feed != null) {
		fav_chanToMonitor = fav_object.getChannelList(g_Feed.channels, true);
		return true;
	}
	return false;
}

function fav_setSetupMode() {
	if (vverbose) {
		log(__FUNCTION());
	}
	fav_optgroup = xml_favouriteProgramSelect;
	fav_input = xml_favProgramInput;
	xml_hideCompletedPrograms.value = prefs.hidePreviousPrograms == false ? 0 : 1;
	xml_monitorUseSound.value = !!parseInt(options.getValue("TVTID.Sound.Active")) == 1;
	xml_monitorMediaFile.value = options.getValue("TVTID.Sound.Filename");
	xml_dropzoneLabel.innerText += " " + xml_monitorMediaFile.value;
	xml_monitorIntervalBefore.value = fav_monitorWindow[0];
	xml_monitorIntervalAfter.value = fav_monitorWindow[1];
	var date = new Date;
	xml_suggestDayOfWeek.children.item("d" + date.getDay()).selected = true;
	var h = date.getHours();
	if (h % 2 == 0) {
		h--;
	}
	xml_suggestTimeOfDay.children.item("t" + ((h + "").length == 1 ? "0" + h : h)).selected = true;
	fav_object.setTimeInterval();
	setTimeout(function () {
		fav_object.writeProgramOptions();
	}, 150);
}

function fav_createSuggest(inputElement) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var pos = [inputElement.x, inputElement.y];
	pos[0] += 1;
	pos[1] += 21;
	var suggest = xml_favProgramContainer.appendElement("<div width=\"194\" background=\"#0C0C0C\" x=\"" + pos[0] + "\" y=\"" + pos[1] + "\"></div>");
	var inner = suggest.appendElement(fav_suggest1);
	var button = inner.appendElement(fav_suggest2);
	button.onclick = function () {
		fav_suggestionBox.visible = false;
	};

	inner.appendElement(fav_suggest3);
	inner.appendElement(fav_suggest4);
	return suggest;
}

function fav_hideGuide() {
	if (vvverbose) {
		log(__FUNCTION());
	}
	fav_guidelineTimer != null && clearTimeout(fav_guidelineTimer);
	fav_guidelineTimer = setTimeout(function () {
		if (typeof addremove != "undefined") {
			addremove.visible = false;
		}
	}, 3000);
}

function fav_showGuide(chanId, progId) {
	if (vvverbose) {
		log(__FUNCTION());
	}
	fav_guidelineTimer != null && clearTimeout(fav_guidelineTimer);
	var anchor = eval("d_chan" + chanId + "_prog" + progId).children.item("pTitle");
	var channel = g_Feed.channels[chanId];
	var program = channel.program[progId];
	var pos = findPos(anchor);
	if (program && program.title.indexOf(",") != -1) {
		return;
	}
	var search = "," + options.getValue("TVTID.Monitor.Programs") + ",";
	if (typeof addremove == "undefined") {
		try {
			addremove = xml_mainContainer.appendElement("<button width=\"18\" height=\"18\" name=\"addremove\" />");
		} catch (e) {}
		addremove.onmouseover = function () {
			fav_guidelineTimer != null && clearTimeout(fav_guidelineTimer);
		};

		addremove.onmouseout = fav_hideGuide;
	} else {
		addremove.visible = true;
	}
	fav_guideline = anchor;
	anchor.color = "#D0D0D0";
	addremove.x = "17%";
	addremove.y = pos.y - 34;
	addremove.onclick = function () {
		fav_object.guidelineRegisterEvent(chanId, progId);
		fav_guideline.color = "#AEAEAE";
	};

	if (RegExp("," + channel.name.replace("+", "\\+").replace(".", "\\.").replace("?|*", ".") + "\\|" + program.title + ",").test(search)) {
		addremove.image = "images/nav/left.png";
		addremove.tooltip = "Fjern fra Favoritliste";
	} else {
		addremove.tooltip = "Adder program til Favoritliste";
		addremove.image = "images/nav/right.png";
	}
	fav_guidelineTimer = setTimeout(function () {
		if (typeof addremove != "undefined") {
			d.visible = false;
			fav_guideline.color = "#AEAEAE";
		}
	}, 15000);
}

function fav_onSetTimeInterval(resText) {
	if (vverbose) {
		log(__FUNCTION());
	}
	if (resText) {
		try {
			g_Feed = eval("(" + resText + ")");

		} catch (e) {
			alert("Interval returns 404");
			return false;
		}
	}
	fav_chanArray = fav_object.getChannelList(g_Feed.channels);
	if (opt_activePage == xml_settingsPage_1 && xml_favProgramInput.value.length > 0) {
		this.lookupProgram(xml_favProgramInput);
	}
	return true;
}

function fav_getClosestDateFromDay(day) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var now = new Date;
	var d = now.getDay();
	d = day - d;
	now = new Date(now.setDate(now.getDate() + d));
	return now;
}

function FAV() {
	this.instance = true;
}
FAV.prototype.init = function fav_init() {
	if (vverbose) {
		log(__FUNCTION());
	}
	if (fav_initialized) {
		return this;
	}
	fav_initialized = true;
	if (g_Feed != null) {
		fav_chanArray = this.getChannelList(g_Feed.channels);
	}
	fav_monitorWindow = options.getValue("TVTID.Monitor.Interval").split(",");
	if (fav_monitorWindow[1] == null) {
		fav_monitorWindow = [30, 10];
	}
	if (typeof xml_favouriteProgramSelect != "undefined") {
		fav_setSetupMode();
		fav_buf1 = fav_buf2 = fav_buf3 = fav_buf4 = null;
	} else {
		var self = this;
		setInterval(function () {
			self.monitor();
		}, 60000);
		if (fav_loadMonitor()) {
			this.monitor();
		}
		fav_suggest1 = fav_suggest2 = fav_suggest3 = fav_suggest4 = null;
	}
	Sound.load();
	return this;
};

FAV.prototype.monitor = function fav_monitor() {
if(vverbose) log(__FUNCTION());
	if (!fav_initialized) {
		throw "Must run init prior to monitoring";
	}
	if (g_Feed == null) {
		return;
	}
	if (fav_chanToMonitor.length < 1) {
		return;
	}

	var progList = options.getValue("TVTID.Monitor.Programs").split(",");
	if (progList.length == 0 || progList[0] == "") {
		return;
	} while (fav_upcomingPrograms.pop()) {}
	var pitem ;
	var start, NOW = Math.floor((new Date).getTime() / 1000);
	for (i = 0; i < progList.length; i++) {
		pitem = progList[i].substring(progList[i].indexOf("|") + 1);
		//exp = RegExp(progList[i].substring(progList[i].indexOf("|") + 1).replace(/\ /g, "\\ "), "i");

		for (var j = 0; j < fav_chanToMonitor.length; j++) {
			for (var k = 0; k < fav_chanToMonitor[j].program.length; k++) {
				start = fav_chanToMonitor[j].program[k].start_timestamp;
//				if (exp.test(fav_chanToMonitor[j].program[k].title) && NOW > start - 60 * fav_monitorWindow[0] && NOW < start + 60 * fav_monitorWindow[1]) {
				if (( pitem == fav_chanToMonitor[j].program[k].title)) {

					if(NOW > start - 60 * fav_monitorWindow[0] && NOW < start + 60 * fav_monitorWindow[1]) {
log("hier"+ pitem);
						fav_upcomingPrograms.push(fav_chanToMonitor[j].program[k]);
						fav_upcomingPrograms[fav_upcomingPrograms.length-1].channel = fav_chanToMonitor[j].name;
					}
				}
			}
		}
	}
	if (fav_upcomingPrograms.length > 0) {
		Sound.play();
		this.showMonitor();
	}
};
FAV.prototype.hideMonitor = function fav_hideMonitor() {
	notify_outer.visible = false;
}
FAV.prototype.animation = null;
FAV.prototype.animate = function fav_anim() {
	var val = event.value > 360 ? event.value-360 : event.value
	xml_notifySpinner.rotation = val;
	if(val > 270)
		xml_notifySpinner.color = "red"
	else if(val > 180) 
		xml_notifySpinner.color = "orange"
	else if(val > 90)
		xml_notifySpinner.color = "white"
	else 
		xml_notifySpinner.color = "yellow"
	if(event.value > 795) xml_notifySpinner.size = "12"
}
FAV.prototype.showMonitor = function fav_showMonitor() {
if(vverbose) log(__FUNCTION());
log(typeof xml_notifyText);
	if(xml_notifyOuter.visible)
		return;
	if(options.exists("TVTID.Monitor.snoozeTime")) {
		var snooze = options.getValue("TVTID.Monitor.snoozeTime");
		var till = new Date(snooze);
		till.setMinutes(till.getMinutes() + 9);
		if(new Date().getTime() < till.getTime()) 
			return ;
	}
	var self = this;
	this.animation = setInterval(function() {
		xml_notifySpinner.size = "9"
		view.beginAnimation(self.animate, 20, 820, 1500);
	}, 3000);
	Sound.play();
	var program = fav_upcomingPrograms[0];
	xml_notifyOuter.visible  = true;
log(program.start + " på " + program.channel + ": " + program.title);
	xml_notifyText.innerText = program.start + " på " + program.channel + ":\n    " + program.title;
//	notify.launch(program.channel+" - " + program.title, program.title + ", kl. "+ program.start + " på " + program.channel, "http://tvtid.tv2.dk/program/index.php/id-"+program.program_id+".html");

//	opendetails(strings.UPCOMING_PROGRAMS, fav_buildMonitor());
};

FAV.prototype.update = function fav_update() {
	fav_chanArray = this.getChannelList(g_Feed.channels);
	fav_input.value = "";
};

FAV.prototype.saveProgramSettings = function fav_save() {
	var opt = "", chan = "", cur;
	var i = 0;
	for (var iter = new Enumerator(xml_favouriteProgramSelect.children); !iter.atEnd(); iter.moveNext()) {
		if (i++ == 0) {
			continue;
		}
		el = iter.item();
		cur = [];
		for (var lIter = new Enumerator(el.children); !lIter.atEnd(); lIter.moveNext()) {
			cur.push(lIter.item().innerText);
		}
		cur = cur.join("|");
		RegExp("^" + cur.substring(0, cur.indexOf("|")) + "$") && (chan += cur.substring(0, cur.indexOf("|")));
		opt += cur;
		if (i < fav_optgroup.children.count) {
			opt += ",";
			chan.lastIndexOf(",") != chan.length - 1 && (chan += ",");
		}
	}
log("CHANNELS: " + chan);
	options.putValue("TVTID.Monitor.Programs", opt);
options.putValue("TVTID.Monitor.Interval", fav_monitorWindow.join(","));
options.putValue("TVTID.Monitor.Channels", chan);
options.putValue("TVTID.Sound.Active", xml_monitorUseSound.value ? 1 : 0);
options.putValue("TVTID.Sound.Filename", xml_monitorMediaFile.value);
options.putValue("TVTID.Channel.HideCompleted", xml_hideCompletedPrograms ? 1 : 0);
};

FAV.prototype.writeProgramOptions = function fav_write(single) {
	if (typeof single == "string" && single != "" && single.indexOf("|") != -1) {
		el = fav_optgroup.appendElement("<item></item>");
		el.appendElement("<label name=\"lChan\" width=\"18%\" x=\"4\">" + single.split("|")[0] + "</label>");
		el.appendElement("<label name=\"pTitle\" x=\"20%\" width=\"80%\">" + single.split("|")[1] + "</label>");
		return;
	}
	var opt = options.getValue("TVTID.Monitor.Programs"), el;
	if (opt == "") {
		return;
	}
	log("write: " + opt);
	opt = opt.split(",");
	for (var i = 0; i < opt.length; i++) {
		el = fav_optgroup.appendElement("<item></item>");
		el.appendElement("<label width=\"18%\" x=\"4\">" + opt[i].split("|")[0] + "</label>");
		el.appendElement("<label x=\"20%\" width=\"80%\">" + opt[i].split("|")[1] + "</label>");
	}
	};

FAV.prototype.registerProgram = function fav_register() {
	if (fav_input.value.indexOf("|") < 2) {
		alert(strings.js_SEARCH_FEEDBACK1);
		return;
	}
	if (fav_input.value.indexOf(",") != -1) {
		alert(strings.js_SEARCH_FEEDBACK2);
		fav_input.value = "";
		return;
	}
	var exp = new RegExp("^" + fav_input.value.substring(0, fav_input.value.indexOf("|")).replace(/[\ ]*\|/, "") + "$", "i");
	var g2g = false, el;
	for (var i = 0; i < fav_chanArray.length; i++) {
		if (exp.test(fav_chanArray[i].name)) {
			g2g = true;
		}
	}
	if (g2g) {
	var trim = fav_input.value.replace(/[\ ]*\|/, "|").replace(/\|[\ ]*/, "|");
	this.writeProgramOptions(trim);
	fav_input.value = "";
	fav_closeSuggest();
} else {
	alert(strings.js_SEARCH_FEEDBACK3);
}
};

FAV.prototype.unregisterProgram = function fav_unregister() {
	fav_optgroup.removeElement(fav_optgroup.selectedItem);
};

FAV.prototype.guidelineHideControl = function fav_guidehide() {
	fav_hideGuide();
};

FAV.prototype.guidelineShowControl = function fav_guideshow(chanId, progId) {
	if (vvverbose) {
		log(__FUNCTION());
	}
	fav_showGuide(chanId, progId);
};

FAV.prototype.guidelineRegisterEvent = function fav_guideregister(chanID, progID) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var buf, setting = options.getValue("TVTID.Monitor.Programs");
	if (/right/.test(eval("addremove").image)) {
		buf = setting.length > 1 ? "," : "";
		buf += g_Feed.channels[chanID].name + "|" + g_Feed.channels[chanID].program[progID].title;
		options.putValue("TVTID.Monitor.Programs", setting + buf);
		eval("addremove").image = "images/nav/left.png";
		addremove.tooltip = strings.tt_ADDREMOVE1;
	} else {
		eval("addremove").tooltip = strings.tt_ADDREMOVE2;
		addremove.image = "images/nav/right.png";
		buf = "[,]?" + g_Feed.channels[chanID].name + "\\|" + g_Feed.channels[chanID].program[progID].title;
		setting = setting.replace(RegExp(buf.replace("+", "\\+").replace(".", "\\.").replace("?|*", ".")), "");
		options.putValue("TVTID.Monitor.Programs", setting.indexOf(",") == 0 ? setting.substring(1) : setting);
	}
};

FAV.prototype.getChannelList = function fav_getchannels(monitored) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var search, favouriteArray = [];
	if (typeof xml_favouriteChannels != "undefined") {
		if (xml_favouriteChannels.children.count == 0) {
			alert("Jitter occured doing XMLHTTP, please re-open the options dialog");
			return;
		}
		prefs.myChannels = [];
		var iter = new Enumerator(xml_favouriteChannels.children), el;
		while (!iter.atEnd()) {
			el = iter.item();
			prefs.myChannels.push(trueChanId(el.name.replace("chan_", "")).trim());
			iter.moveNext();
		}
		search = "," + prefs.myChannels.join(",") + ",";
	} else if (monitored == true) {
		search = "," + options.getValue("TVTID.Monitor.Channels") + ",";
	} else {
		search = "," + prefs.channels.favourites + ",";
	}
	for (var i = 0; i < g_Feed.channels.length; i++) {
		if (RegExp("[^ ]" + g_Feed.channels[i].name + "[^ ]").test(search)) {
			favouriteArray.push(g_Feed.channels[i]);
		}
	}
	return favouriteArray;
};

FAV.prototype.lookupProgram = function fav_lookup(inputElement) {
	if (vverbose) {
		log(__FUNCTION());
	}
	var token = inputElement.value, exp;
	if (token.length == 0) {
		return fav_closeSuggest();
	} else if (token.length < 3 && fav_lastSearch.length < token.length) {
		return;
	}
	fav_lastSearch = token;
	token.indexOf("|") != -1 && (token = token.substring(token.indexOf("|") + 1).trim());
	if (!def(fav_suggestionBox)) {
		fav_suggestionBox = fav_createSuggest(inputElement);
	}
	try {
		exp = new RegExp(token, "i");
	} catch (e) {
		return fav_closeSuggest();
	}
	var programNames = [];
	for (var i = 0; i < fav_chanArray.length; i++) {
		for (var j = 0; j < fav_chanArray[i].program.length; j++) {
			if (exp.test(fav_chanArray[i].program[j].title)) {
				programNames.push(fav_chanArray[i].name + "|" + fav_chanArray[i].program[j].title);
			}
		}
		}
	xml_suggestionsContainer.removeAllElements();
if (programNames.length > 0) {
	if (g_Feed != null) {
		xml_time_slice.innerText = "Guide interval: " + g_Feed.time_slice;
	}
	fav_suggestionBox.height = 14;
	var setEv = function (anchor, name) {
		anchor.onmousedown = function () {
			fav_object.fillFromSuggest(name);
		};

};

for (i = 0; i < programNames.length; i++) {
	var a = xml_suggestionsContainer.appendElement("<a width=\"96%\" height=\"12\" size=\"7\" x=\"5\" y=\"" + i * 12 + "\">" + programNames[i] + "</a>");
	setEv(a, programNames[i].replace(/'/g, "\""));
	fav_suggestionBox.height += 12;
}
fav_suggestionBox.visible = true;
fav_suggestionBox.height += 2;
if (fav_suggestionBox.height > 130) {
	fav_suggestionBox.height = 130;
	xml_suggestionsInner.height = 126;
} else {
	xml_suggestionsInner.height = fav_suggestionBox.height - 2;
}
} else {
	fav_closeSuggest();
}
};

FAV.prototype.fillFromSuggest = function fav_autocomplete(data) {
	if (vverbose) {
		log(__FUNCTION());
	}
	xml_favProgramInput.value = data;
};

FAV.prototype.setTimeInterval = function fav_setTime() {
	if (vverbose) {
		log(__FUNCTION());
	}
	var d = parseInt(xml_suggestDayOfWeek.selectedItem.name.substring(1));
	d = fav_getClosestDateFromDay(d).getDate();
	var h = parseInt(xml_suggestTimeOfDay.selectedItem.name.substring(1));
	var icon = typeof xml_ajaxIcon != "undefined" ? xml_ajaxIcon : null;
	if (icon != null) {
		icon.visible = true;
	}
	if (g_Feed != null) {
		var now = new Date;
		var feedNow = new Date(g_Feed.page_time.start * 1000);
		if (h == feedNow.getHours() && d == feedNow.getDate()) {
			fav_onSetTimeInterval();
			return;
		}
	}
	fav_onSetTimeInterval(getFeed(null, d, h));
};

FAV.prototype.snooze = function fav_snooze() {
	options.putValue("TVTID.Monitor.snoozeTime", new Date().getTime());
}
return {
	init:function fav_init() {
		if (fav_object != null) {
			return fav_object;
		}
		fav_object = new FAV;
		return fav_object.init();
	},
	getInstance:function () {
		if (fav_object == null) {
			throw "Was not initialized.. check ctor chains plz";
		}
		return fav_object;
	},
	saveProgramSettings:function () {
		if (fav_object == null) {
			throw "Was not initialized.. check ctor chains plz";
		}
		fav_object.saveProgramSettings();
	}
};

})();
